﻿#pragma once

#include "pdh.h"
#include "Source.h"

class Cpu:Source
{
public:
    Cpu();
    ~Cpu() override
    {

        delete this->_cpu;
        delete this->_memory;
        delete this->_pMemoryStatus;
        delete this->_pLastIdleTime;
        delete this->_pLastKernelTime;
        delete this->_pLastUserTime;
    }
    
    boolean doFrame() override
    {
        this->_invokeTimes += 1;
        if(this->_invokeTimes == this->_invokeFrame)
        {
            this->_invokeTimes = 0;
            // 获取cpu利用率
            FILETIME lastIdleTime = *this->_pLastIdleTime;
            FILETIME lastKernelTime = *this->_pLastKernelTime;
            FILETIME lastUserTime = *this->_pLastUserTime;
            GetSystemTimes(this->_pLastIdleTime, this->_pLastKernelTime, this->_pLastUserTime);
            int idle = this->compareTime(&lastIdleTime, this->_pLastIdleTime);
            int kernel = this->compareTime(&lastKernelTime, this->_pLastKernelTime);
            int user = this->compareTime(&lastUserTime, this->_pLastUserTime);
            this->dealCpu(idle, kernel, user);
            GlobalMemoryStatusEx(this->_pMemoryStatus);
            this->dealMemory();
            return true;
        }
        return false;
    }

    void setInvokeFrame(USHORT frame);
    char* getCpuRate() const;
    char* getMemory() const;
private:
    char* _cpu = nullptr;
    char* _memory = nullptr;
    MEMORYSTATUSEX* _pMemoryStatus = nullptr;
    USHORT _invokeFrame = 60;
    USHORT _invokeTimes = 0;
    FILETIME* _pLastIdleTime = nullptr;
    FILETIME* _pLastKernelTime = nullptr;
    FILETIME* _pLastUserTime = nullptr;
    
    void dealCpu(int idel, int kernel, int user) const;
    void dealMemory() const;
    __int64 timeToInt(const FILETIME* fTime) const;
    __int64 compareTime(const FILETIME* lastTime, const FILETIME* nowTime) const;
    
};
